package com.detection.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.dahuatech.icc.exception.ClientException;
import com.dahuatech.icc.oauth.utils.HttpUtils;
import com.detection.common.config.DetectionConfig;
import com.detection.common.utils.spring.SpringUtils;
import com.detection.dahua.config.OauthConfigUtil;
import com.detection.dahua.demo.video.realTimePreview.RealTimePreviewDemo;
import com.detection.dahua.model.video.realTimePreview.HlsUrlRequest;
import com.detection.dahua.model.video.realTimePreview.HlsUrlResponse;
import com.detection.hikvision.domain.CameraPreviewResultView;
import com.detection.hikvision.service.ArtemisCamerasService;
import com.detection.tcp.domain.TCPMessage;
import com.detection.tcp.utils.CameraDetectionStatusUtils;
import com.detection.yolo.service.CameraDetectionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.Objects;

@RestController
@RequestMapping("/tcp")
public class TCPController {
    @Autowired
    private ArtemisCamerasService artemisCamerasService;
    @Autowired
    private CameraDetectionService cameraDetectionService;
    private void startHaiKangDevice(String indexCode, String cameraName, String supportAlgorithms){
        CameraPreviewResultView cameraPreviewUrls = artemisCamerasService.getCameraPreviewUrls(indexCode, 1, "rtsp", 1);
        String url = cameraPreviewUrls.getData().getUrl();
        cameraDetectionService.startDetection(indexCode+"wlw", cameraName, url, supportAlgorithms);
    }

    private void startDahuaDevice(String indexCode, String cameraName, String channelId, String streamType, String type, String supportAlgorithms) throws ClientException {
        RealTimePreviewDemo realTimePreviewDemo = SpringUtils.getBean(RealTimePreviewDemo.class);
        String token = HttpUtils.getToken(OauthConfigUtil.getOauthConfig()).getAccess_token();
        HlsUrlRequest hlsUrlRequest = new HlsUrlRequest();
        HlsUrlRequest.Data data = new HlsUrlRequest.Data();
        data.setChannelId(channelId);
        data.setStreamType(streamType);
        data.setType(type);
        hlsUrlRequest.setData(data);
        HlsUrlResponse hlsUrlResponse = realTimePreviewDemo.getHlsUrl(hlsUrlRequest);
        String hlsPath = hlsUrlResponse.getData().getUrl();
        if (!StringUtils.isEmpty(token)) {
            hlsPath += "?token=" + token;
        }
        if (Objects.isNull(cameraName)) {
            cameraName = channelId;
        }

        hlsPath = parseAndResolveUrl(hlsPath, OauthConfigUtil.getOauthConfig().getHttpConfigInfo().getHost());
        cameraDetectionService.startDetection(indexCode+"wlw", cameraName, hlsPath, supportAlgorithms);
    }
    /**
     * 解析大華可用的視頻地址
     * @param urlList
     * @param targetIp
     * @return
     */
    private static String parseAndResolveUrl(String urlList, String targetIp) {
        if (urlList == null || urlList.trim().isEmpty()) {
            throw new IllegalArgumentException("URL列表不能为空");
        }
        if (targetIp == null || targetIp.trim().isEmpty()) {
            throw new IllegalArgumentException("目标IP不能为空");
        }

        String[] urls = urlList.split("\\|");
        // 去除空白字符串
        urls = Arrays.stream(urls)
                .filter(s -> !s.trim().isEmpty())
                .toArray(String[]::new);

        if (urls.length == 0) {
            throw new IllegalArgumentException("未解析到有效URL");
        }

        // 遍历每个 URL，检查其 IP 是否等于目标 IP
        for (String url : urls) {
            try {
                URI uri = new URI(url.trim());
                String host = uri.getHost();
                if (targetIp.equals(host)) {
                    return url.trim(); // 找到匹配的 IP，直接返回该 URL
                }
            } catch (URISyntaxException e) {
                throw new IllegalArgumentException("无效的URL格式: " + url, e);
            }
        }

        // 如果没有找到匹配的 URL，则修改第一个 URL 的 IP
        try {
            URI firstUri = new URI(urls[0].trim());
            URI updatedUri = new URI(
                    firstUri.getScheme(),
                    firstUri.getUserInfo(),
                    targetIp, // 替换为指定 IP
                    firstUri.getPort(),
                    firstUri.getPath(),
                    firstUri.getQuery(),
                    firstUri.getFragment()
            );
            return updatedUri.toString();
        } catch (URISyntaxException e) {
            throw new IllegalArgumentException("第一个URL格式不正确: " + urls[0], e);
        }
    }

    @PostMapping("/sendmessage")
    public TCPMessage sendMessage(@RequestBody TCPMessage message) {

        try {
            String flag = message.getFlag();
            switch (flag) {
                case "startDetectionVideo":
                    JSONObject dataObj = JSON.parseObject(JSON.toJSONString(message.getData()));
                    String cameraName = dataObj.getString("cameraName");
                    String channelId = dataObj.getString("channelId");
                    String streamType = dataObj.getString("streamType");
                    String type = dataObj.getString("type");
                    String supportAlgorithms = dataObj.getString("supportAlgorithms");
                    if("hikvision".equals(DetectionConfig.getIOTplatform())){
                        startHaiKangDevice(channelId,cameraName,supportAlgorithms);
                    }else if("dahua".equals(DetectionConfig.getIOTplatform())){
                        startDahuaDevice(channelId, cameraName, channelId, streamType, type, supportAlgorithms);
                    }
                    break;
                case "firstStartStatusWLW":
                    if (!CameraDetectionStatusUtils.SoftFirstStartStatus.get("firstStartStatusWLW")) {
                        CameraDetectionStatusUtils.SoftFirstStartStatus.replace("firstStartStatusWLW", true);
                        JSONArray firstStartStatusArrays = JSON.parseArray(JSON.toJSONString(message.getData()));
                        for (int i = 0; i < firstStartStatusArrays.size(); i++) {
                            JSONObject oneObj = firstStartStatusArrays.getJSONObject(i);
                            String indexCode = oneObj.getString("indexCode");
                            String name = oneObj.getString("name");
                            String supportAlgorithms1 = oneObj.getString("supportAlgorithms");
                            if("hikvision".equals(DetectionConfig.getIOTplatform())){
                                startHaiKangDevice(indexCode,name,supportAlgorithms1);
                            }else if("dahua".equals(DetectionConfig.getIOTplatform())){
                                startDahuaDevice(indexCode, name, indexCode, "2", "hls", supportAlgorithms1);
                            }
                            Thread.sleep(200);
                        }
                    }

                    break;
                case "stopDetectionVideo":
                    JSONObject stopDetectionVideoObj = JSON.parseObject(JSON.toJSONString(message.getData()));
                    String indexCode = stopDetectionVideoObj.getString("indexCode");
                    CameraDetectionStatusUtils.CameraDetectionStatusMap.replace(indexCode+"wlw", true);
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }

        return new TCPMessage();
    }


}
